package com.bwie.service.impl;

import com.bwie.exception.BusinessException;
import com.bwie.mapper.ApplyMapper;
import com.bwie.mapper.OrderParkMapper;
import com.bwie.mapper.ShenMapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.po.Apply;
import com.bwie.pojo.po.Shen;
import com.bwie.pojo.po.User;
import com.bwie.service.ShenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;

@Service
public class ShenServiceImpl implements ShenService {
    @Autowired
    private ShenMapper shenMapper;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private OrderParkMapper orderParkMapper;
    @Transactional
    @Override
    public void addShen(Shen shen) {
        //非空校验
        Integer applyId = shen.getApplyId();
        Integer shenType = shen.getShenType();
        if (applyId==null||shenType==null){
            throw new BusinessException("必要字段不能为空");
        }
        //驳回必须填写意见
        if (shenType==1){
            if (StringUtils.isEmpty(shen.getShenRemarks())){
                throw new BusinessException("审批驳回审核意见不能为空！！！");
            }
        }

        //获取申请的信息
        Apply apply = applyMapper.getApplyById(applyId);

        //余额支付
        if (apply.getRechargeType()==0){
            //退款
            BigDecimal sumMoney = apply.getSumMoney();
            Integer userId = apply.getUserId();
            userMapper.updMoney1(userId,sumMoney);
        }


        User user = (User) session.getAttribute("user");

        //新增审批记录
        Shen shen1 = new Shen();
        BeanUtils.copyProperties(shen,shen1);
        shen1.setUserId(user.getUserId());
        shen1.setShenTime(new Date());
        shenMapper.addShen(shen1);



        //修改申请记录的状态
        Integer applyType=0;
        if (shen.getShenType()==0){
            applyType=1;
        } else if (shen.getShenType() == 1) {
            applyType=2;
        }
        Date updTime = new Date();
        applyMapper.updApplyById(applyType,updTime,applyId);



        //修改预定车位列表的退款状态
        Integer orderParkId = apply.getOrderParkId();
        Integer backType = 0;
        if (shen.getShenType()==0){
            backType=1;
        } else if (shen.getShenType() == 1) {
            backType=2;
        }
        orderParkMapper.updOrderParkBackType(orderParkId,backType);

    }
}
